"""Sync the list of files to the given S3 Bucket."""
import argparse
import os
import sys

from cki_lib import misc
from cki_lib.logger import get_logger
from cki_lib.session import get_session
from cki_lib.yaml import load
from requests.exceptions import RequestException
import sentry_sdk

from cki.cki_tools._utils import S3Bucket

LOGGER = get_logger('cki.cki_tools.sync_files')
SESSION = get_session('cki.cki_tools.sync_files', raise_for_status=True)

BUCKET_CONFIG_NAME = os.environ.get('BUCKET_CONFIG_NAME')
SYNC_CONFIG = load(contents=os.environ.get('SYNC_FILES_CONFIG'),
                   file_path=os.environ.get('SYNC_FILES_CONFIG_PATH'))


def sync_file(bucket, source_url, target_path):
    """Return True if the file was synced to the bucket, otherwise False."""
    LOGGER.info('Fetching %s ...', source_url)
    try:
        response = SESSION.get(source_url)
    except RequestException as err:
        LOGGER.warning("Problem fetching '%s':\n%s", source_url, err)
        return False

    LOGGER.info('Uploading %s bytes to %s', response.headers['content-length'], target_path)
    if misc.is_production():
        bucket.client.put_object(
            Bucket=bucket.spec.bucket,
            Key=bucket.spec.prefix + target_path,
            Body=response.text,
            ContentType=response.headers['content-type'].split(';')[0],
        )
    return True


def main(args: list[str] | None = None) -> None:
    """Do the work."""
    parser = argparse.ArgumentParser()
    parser.parse_args(args)

    ret_val = 0
    if flist := SYNC_CONFIG.get('file_list', []) if SYNC_CONFIG else []:
        LOGGER.info('%s file%s to sync: %s', len(flist), '' if len(flist) == 1 else 's', flist)
        bucket = S3Bucket.from_bucket_string(os.environ[BUCKET_CONFIG_NAME])
        if not all(sync_file(bucket, **file_spec) for file_spec in flist):
            ret_val = 1
    else:
        LOGGER.info('Empty sync files config, nothing to do.')
        ret_val = -1
    sys.exit(ret_val)


if __name__ == '__main__':
    misc.sentry_init(sentry_sdk, ca_certs=os.environ.get('REQUESTS_CA_BUNDLE'))
    main()
